package com.atguigu.gmall.pay.controller;

import com.alibaba.fastjson.JSON;
import com.alipay.api.AlipayApiException;
import com.alipay.api.internal.util.AlipaySignature;
import com.atguigu.gmall.pay.properties.AlipayProperties;
import com.atguigu.gmall.pay.service.PayService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

@RestController
@RequestMapping(value = "/api/payment")
@Slf4j
public class PayController {

    @Autowired
    private PayService payService ;

    @Autowired
    private AlipayProperties alipayProperties ;

    @Autowired
    private RabbitTemplate rabbitTemplate ;

    @GetMapping(value = "/alipay/submit/{orderId}")
    public String pay(@PathVariable(value = "orderId") String orderId) {
        return payService.pay(orderId) ;
    }

    @PostMapping(value = "/alipay/listenpayed")
    public String listenpayed(@RequestParam Map<String , String> map) {

        try {

            // 对数据进行校验
            boolean signVerified = AlipaySignature.rsaCheckV1(map, alipayProperties.getAlipayPublicKey(), alipayProperties.getCharset(), alipayProperties.getSignType());
            if(signVerified) {      // 校验通过

                log.info("map: {}" , JSON.toJSONString(map));

                // 更改订单的状态
                rabbitTemplate.convertAndSend("payed.exchange" , "order.payed" , JSON.toJSONString(map));

                // 返回
                return "success" ;

            }else {
                log.info("数据校验未通过了....");
                return "error" ;
            }

        } catch (AlipayApiException e) {
            throw new RuntimeException(e);
        }

    }

}
